import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xvideos/hj_model/home/module_detail_model.dart';
import 'package:xvideos/hj_utils/widget_utils.dart';
import 'package:xvideos/tools_base/loading/l_error_widget.dart';
import 'package:xvideos/tools_base/loading/loading_center_widget.dart';
import 'package:xvideos/tools_base/refresh/pull_refresh.dart';

import '../../home_business/widget/home_section_tab_menu.dart';
import 'pic_grid_logic.dart';
import 'pic_sets_cell.dart';

class PicGridPage extends StatefulWidget {
  final AllSection? section;
  const PicGridPage({super.key, this.section});

  @override
  State<PicGridPage> createState() => _PicGridPageState();
}

class _PicGridPageState extends State<PicGridPage> {
  late PicGridLogic logic;
  late String tag;

  @override
  void initState() {
    super.initState();
    tag = (widget.section?.sectionName ?? '') + (widget.section!.sectionID ?? '');
    logic = Get.put(PicGridLogic(section: widget.section), tag: tag);
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<PicGridLogic>(
        tag: tag,
        builder: (_) {
          return Column(
            children: [
              if (_.section?.type != -100 && _.section?.type != -101) ...[
                _buildTabbarView(),
                10.sizeBoxH,
              ],
              GetBuilder<PicGridLogic>(
                tag: tag,
                id: 'list',
                builder: (controller) => Expanded(child: _buildContent(_)),
              ),
            ],
          );
        });
  }

  _buildContent(PicGridLogic _) {
    if (_.allMediaInfo == null) return LoadingCenterWidget();
    return pullYsRefresh(
      onInit: (ctr) => logic.refreshCtr = ctr,
      onRefresh: (ctr) => _.loadData(),
      onLoading: (ctr) => _.loadMoreData(),
      child: (_.allMediaInfo != null && _.allMediaInfo?.isEmpty == true)
          ? CErrorWidget()
          : GridView.builder(
              padding: EdgeInsets.only(top: 0, right: 16),
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                mainAxisSpacing: 12,
                crossAxisSpacing: 7,
                childAspectRatio: 136 / 204,
              ),
              itemCount: _.allMediaInfo?.length ?? 0,
              itemBuilder: (context, index) {
                return PicSetsCell(
                  videoModel: _.allMediaInfo?[index],
                  allBorder: true,
                );
              },
            ),
    );
  }

  //tabbar
  _buildTabbarView() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        HomeSectionTabMenu(
          (logic.tabs.map((e) => e)).toList(),
          curIndex: 0,
          tabController: logic.tabCtr,
          padding: EdgeInsets.symmetric(horizontal: 12, vertical: 2),
        ),
      ],
    );
  }
}
